﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using WeChat.Common2;

namespace WeChat.Common
{
    /// <summary>
    /// 模板消息
    /// </summary>
    public class TemplateAction
    {
        /// <summary>
        /// 帐户资金变动提醒模板消息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="template_id"></param>
        /// <param name="time"></param>
        /// <param name="addMoney"></param>
        /// <param name="amount"></param>
        /// <return>errcode</return>
        public static string sendTemplateMsg(string openid, string template_id,string time,string addMoney,string amount)
        {
            string accesstoken = GetAccess_token.getAccesstoken();
            string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accesstoken;

            JObject jo = new JObject();

            JObject jc = new JObject();
            jc.Add("first", getTemplateList("您好，您充值的金额已到账！", "#173177"));
            jc.Add("date", getTemplateList(time, "#173177"));
            jc.Add("adCharge", getTemplateList(addMoney + " 元", "#173177"));
            jc.Add("type", getTemplateList("当前", "#000000"));
            jc.Add("cashBalance", getTemplateList(amount + " 元", "#173177"));
            jc.Add("remark", getTemplateList("\n您可以在充值记录中查阅您的帐户记录。", "#173177"));

            jo.Add("touser", openid);
            jo.Add("template_id", template_id);
            jo.Add("url", OAuthHelper.getRedirectUrl("http://" + Config.domainName + "/WeChat/UserInfo/RechargeRecords.aspx"));
            jo.Add("data", jc);
            ApplicationLog.Write("发送帐户资金变动提醒模板消息json:" + jo.ToString());

            string jsons = new GetReturnJson().postReturnJson(url, jo.ToString());
            return JObject.Parse(jsons)["errcode"].ToString();
        }
        //设置模板消息内嵌套json值
        private static JObject getTemplateList(string value, string color)
        {
            JObject jo = new JObject();
            jo.Add("value",value);
            jo.Add("color",color);
            return jo;
        }
    }
}
